<template>
  <div class="permission-manage">
    <!-- 角色选择区域 -->
    <div class="role-select">
      <el-select 
        v-model="selectedRole" 
        placeholder="请选择角色" 
        style="width: 200px"
        @change="handleRoleChange"
        clearable
      >
        <el-option
          v-for="role in roleOptions"
          :key="role.id"
          :label="role.roleName"
          :value="role.id"
        />
      </el-select>
    </div>

    <!-- 权限分配区域 -->
    <div class="permission-content" v-if="selectedRole">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>权限分配</span>
            <div>
              <el-button type="primary" @click="handleSave">保存</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
        </template>
        
        <!-- 模块权限树 -->
        <div class="module-list">
          <div v-for="module in moduleList" :key="module.id" class="module-item">
            <div class="module-header">
              <el-checkbox 
                v-model="module.checked"
                :indeterminate="module.indeterminate"
                @change="(val) => handleModuleCheckChange(val, module)"
              >
                {{ module.moduleName }}
              </el-checkbox>
            </div>
            <div class="function-list">
              <el-checkbox-group v-model="module.selectedFuncs">
                <el-checkbox 
                  v-for="func in module.functions" 
                  :key="func.id" 
                  :label="func.id"
                  @change="() => handleFuncCheckChange(module)"
                >
                  {{ func.funcName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <el-empty v-else description="请选择角色" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';

// 角色选项
const roleOptions = [
  { id: 1, roleName: '超级管理员' },
  { id: 2, roleName: '普通管理员' },
  { id: 3, roleName: '普通用户' }
];

// 模拟模块和功能数据
const moduleList = ref([
  {
    id: 1,
    moduleName: '基础模块',
    checked: false,
    indeterminate: false,
    selectedFuncs: [],
    functions: [
      { id: 1, funcName: '用户查询', funcCode: 'USER_QUERY' },
      { id: 2, funcName: '用户添加', funcCode: 'USER_ADD' },
      { id: 3, funcName: '用户编辑', funcCode: 'USER_EDIT' }
    ]
  },
  {
    id: 2,
    moduleName: '业务模块',
    checked: false,
    indeterminate: false,
    selectedFuncs: [],
    functions: [
      { id: 4, funcName: '任务查询', funcCode: 'TASK_QUERY' },
      { id: 5, funcName: '任务添加', funcCode: 'TASK_ADD' },
      { id: 6, funcName: '任务编辑', funcCode: 'TASK_EDIT' }
    ]
  }
]);

const selectedRole = ref('');
const originalPermissions = ref({}); // 保存原始权限状态

// 角色变更处理
const handleRoleChange = (roleId) => {
  if (!roleId) {
    // 清空选择时重置所有模块的选中状态
    moduleList.value.forEach(module => {
      module.selectedFuncs = [];
      module.checked = false;
      module.indeterminate = false;
    });
    return;
  }

  // 模拟获取角色权限数据
  const permissions = {
    1: [1, 2, 3], // 超级管理员拥有的功能ID
    2: [1, 4], // 普通管理员拥有的功能ID
    3: [1] // 普通用户拥有的功能ID
  };

  // 重置所有模块的选中状态
  moduleList.value.forEach(module => {
    module.selectedFuncs = [];
    module.checked = false;
    module.indeterminate = false;
  });

  // 设置该角色拥有的权限
  if (permissions[roleId]) {
    moduleList.value.forEach(module => {
      const selectedFuncs = module.functions
        .filter(func => permissions[roleId].includes(func.id))
        .map(func => func.id);
      
      module.selectedFuncs = selectedFuncs;
      updateModuleCheckStatus(module);
    });
  }

  // 保存原始权限状态
  originalPermissions.value = JSON.parse(JSON.stringify(
    moduleList.value.map(m => ({
      id: m.id,
      selectedFuncs: [...m.selectedFuncs]
    }))
  ));
};

// 模块选中状态变更
const handleModuleCheckChange = (checked, module) => {
  module.indeterminate = false;
  module.selectedFuncs = checked 
    ? module.functions.map(func => func.id)
    : [];
};

// 功能选中状态变更
const handleFuncCheckChange = (module) => {
  const checkedCount = module.selectedFuncs.length;
  const totalCount = module.functions.length;
  
  module.checked = checkedCount === totalCount;
  module.indeterminate = checkedCount > 0 && checkedCount < totalCount;
};

// 更新模块的选中状态
const updateModuleCheckStatus = (module) => {
  const checkedCount = module.selectedFuncs.length;
  const totalCount = module.functions.length;
  
  module.checked = checkedCount === totalCount;
  module.indeterminate = checkedCount > 0 && checkedCount < totalCount;
};

// 保存权限
const handleSave = () => {
  if (!selectedRole.value) {
    ElMessage.warning('请先选择角色');
    return;
  }

  // 收集所有选中的功能ID
  const permissions = moduleList.value.reduce((acc, module) => {
    return [...acc, ...module.selectedFuncs];
  }, []);

  console.log('保存权限:', {
    roleId: selectedRole.value,
    permissions: permissions
  });

  ElMessage.success('权限保存成功');
  
  // 更新原始权限状态
  originalPermissions.value = JSON.parse(JSON.stringify(
    moduleList.value.map(m => ({
      id: m.id,
      selectedFuncs: [...m.selectedFuncs]
    }))
  ));
};

// 重置权限
const handleReset = () => {
  if (!selectedRole.value) {
    ElMessage.warning('请先选择角色');
    return;
  }

  // 恢复到原始状态
  moduleList.value.forEach(module => {
    const originalModule = originalPermissions.value.find(m => m.id === module.id);
    if (originalModule) {
      module.selectedFuncs = [...originalModule.selectedFuncs];
      updateModuleCheckStatus(module);
    }
  });

  ElMessage.info('已重置为原始状态');
};
</script>

<style scoped>
.permission-manage {
  padding: 20px;
}

.role-select {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.module-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.module-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.module-header {
  margin-bottom: 10px;
  font-weight: bold;
}

.function-list {
  padding-left: 20px;
}

.function-list :deep(.el-checkbox) {
  margin-right: 30px;
  margin-bottom: 10px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style>
